<template>
	<div>
		<div ref="chartRef" class="w-full h-full"></div>
	</div>
</template>

<script setup lang="ts">
import { tryOnUnmounted, useDebounceFn } from '@vueuse/core';
import * as echarts from 'echarts';
import { useEventListener } from '/@/hooks/event/useEventListener';
interface ItemType {
	name: string;
	value: number;
}
const props = defineProps({
	data: {
		type: Array<ItemType>,
		default: () => [],
	},
	color: {
		type: Array<String>,
		default: () => ['#67C23A', '#F56C6C', '#409EFF'],
	},
	title: {
		type: String,
		default: '',
	},
	seriesTitle: {
		type: String,
		default: '',
	},
});
const chartRef = ref();
let resizeFn = resize;
let removeResizeFn = () => {};
let instance: any;
const chartData = reactive<{ legendData: string[]; seriesData: ItemType[] }>({
	legendData: [],
	seriesData: [],
});
resizeFn = useDebounceFn(resize, 200);
watch(
	() => props.data,
	() => {
		getChartData();
		setOptions();
	},
	{
		deep: true,
	}
);
const getChartData = () => {
	chartData.legendData = [];
	chartData.seriesData = [];
	for (let i = 0; i < props.data?.length; i++) {
		const d: ItemType = props.data[i];
		chartData.legendData.push(d.name);
		chartData.seriesData.push(d);
	}
};
const setOptions = () => {
	getChartData();
	const options = {
		color: props.color,
		tooltip: {
			trigger: 'item',
			position: 'right',
			formatter: '{a} <br/>{b}: {c} ({d}%)',
		},
		legend: {
			orient: 'vertical',
			x: 'left',
			itemWidth: 20,
			padding: 0,
			textStyle: { color: '#fff', fontSize: 10 },
			data: chartData.legendData,
		},
		grid: {
			// borderWidth: 0,
			top: 10,
			bottom: 10,
			left: 4,
			right: 0,
			textStyle: {
				color: '#fff',
			},
			containLabel: true,
		},
		series: [
			{
				name: props.seriesTitle,
				type: 'pie',
				radius: ['10%', '60%'],
				// center: ['55%', '50%'],
				// radius: ['50%', '70%'],
				center: ['50%', '45%'],
				minAngle: 2,
				// roseType: 'area',
				itemStyle: {
					borderRadius: 5,
				},
				label: {
					show: true,
					// position: 'outside',
					fontSize: 10,
					color: '#fff',
					z: 9999,
					formatter: '{c}\n{d}%',
					// formatter(param: any) {
					// 	return param.percent ? param.percent + '%' : '';
					// },
				},
				labelLine: {
					// length: 4,
					// length2: 4,
					smooth: true,
				},
				data: chartData.seriesData,
				animationType: 'scale',
				animationEasing: 'exponentialInOut',
				animationDelay: function () {
					return Math.random() * 400;
				},
			},
		],
	};
	instance && instance.clear();
	!instance && (instance = echarts.init(chartRef.value));
	instance.setOption(options);
};
function resize() {
	const config = {
		animation: {
			duration: 200,
			easing: 'quadraticIn',
		},
	};
	instance.resize(config);
}
onMounted(() => {
	setOptions();
	const { removeEvent } = useEventListener({
		el: window,
		name: 'resize',
		listener: resizeFn,
	});
	removeResizeFn = removeEvent;
});

tryOnUnmounted(() => {
	removeResizeFn();
});
</script>
